package util.mapstruct;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @Author liw
 * @Date 2021/4/1 11:02
 * @Version 1.0
 */
public class MapstructTest {
    public static void main(String[] args) throws Exception {

        aa();

    }



    private static void aa() throws Exception {
        //创建源文件
        String currentDir = System.getProperty("user.dir");
        String page = "com.example.demo.mapstruct";
        String className = "TestCompiler";
        String src = "package "+page+" ;\n"
                + "public class "+className+" {\n"
                + " public void disply() {\n"
                + "     System.out.println(\"Hello\");\n"
                + " }\n"
                + "}\n";

        String filename = currentDir + "/src/main/java/com/example/demo/mapstruct/"+className+".java";
        System.out.println(src);
        System.out.println(filename);
        File file = new File(filename);

        File fileParent = file.getParentFile();

        if (!fileParent.exists()) {
            fileParent.mkdir();
        }

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file);
        fw.write(src);
        fw.flush();
        fw.close();

        // 使用JavaCompiler 编译java文件
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();

        String str = "C:\\lw\\project\\test\\demo\\src\\main\\java\\com\\example\\demo\\mapstruct\\TestCompiler1.java";
        int run = jc.run(null, null, null, str);
        System.out.println(run + "int run");

        // 使用URLClassLoader加载class到内存
        URL[] urls1 = new URL[]{new URL("file:/" + str )};
        URLClassLoader cLoader1 = new URLClassLoader(urls1);
        Class c1 = cLoader1.loadClass(page + "." + className + "1");
        cLoader1.close();
        // 利用class创建实例，反射执行方法
        Object obj1 = c1.newInstance();
        Method method1 = c1.getMethod("disply");
        method1.invoke(obj1);

//        StandardJavaFileManager fileManager = jc.getStandardFileManager(null, null, null);
//        Iterable fileObjects = fileManager.getJavaFileObjects(filename);
//        JavaCompiler.CompilationTask cTask = jc.getTask(null, fileManager, null, null, null, fileObjects);
//        cTask.call();
//        fileManager.close();
//
//        // 使用URLClassLoader加载class到内存
//        URL[] urls = new URL[]{new URL("file:/" + filename )};
//        URLClassLoader cLoader = new URLClassLoader(urls);
//        Class c = cLoader.loadClass(page + "." + className);
//        cLoader.close();
//
//        // 利用class创建实例，反射执行方法
//        Object obj = c.newInstance();
//        Method method = c.getMethod("disply");
//        method.invoke(obj);
    }

}
